#!/bin/bash
##############################################################
## @Description effect AtlasEdge upgrade processes
## @Usage edge_upd_effect.sh
## @Options
## @Version V100R020C00RC1
## @Created 2020/08/06
##############################################################

umask 0077
# return code
declare -i ret_ok=0                                 # 成功
declare -i ret_upgrade_failed=1                     # 升级失败
declare -i ret_upgrade_ok_need_restart=2            # 需要升级 需要重启
declare -i ret_failed_dictionary_no_space=3         # 失败 文件夹空间不够
declare -i ret_process_runing_exit=4                # 进程正在运行，退出
declare -i ret_no_satisfy_upgrade_condition=5       # 当前环境不满足 退出 不删除升级包
declare -i ret_failed_copy_file_failed=6            # 失败 拷贝文件失败
declare -i ret_backup_finish_restart=7             # exec backup file restart
declare -i ret_failed_upgrade_mode_exit=8           # 失败 升级模式 退出
declare -i ret_failed_set_upgrade_process_failed=9  # set upgrade process file failed
declare -i ret_no_need_upgrade=10                  # 当前未找到升级包
declare -i ret_effect_ha_failed=11                  # effect ha failed after reboot
declare -i ret_set_edge_effect_flag_fail=12         # set edge effect flag fail after reboot
declare -i ret_effect_restart=13                    # exec effect restart

############ config  export part ###############
declare -i Err_MkHaHandlerFailed=27
declare -i Err_CpHAConfigFailed=28
declare -i Err_CpEdgeDBFailed=29
declare -i Err_TransEdgeCfgFailed=30
declare -i Err_ContainerExportPyFailed=31
declare -i Err_ConfigExportPyFailed=32
PYTHON3=$(type -p python3)

path=$(cd $(dirname $0); pwd)
cd ${path}
#工作目录默认当前目录
WORK_PATH=${path}

# config file
ATLASEDGE_CONFIG_FILE="${WORK_PATH}/config/config.ini"
CORE_CONFIG_FILE="software/edge_core/conf/edgecore.yaml"

# 预升级目录
ATLASEDGE_PRE_UPGRADE_PATH=${WORK_PATH}/edge_upgrade
# 备份目录
ATLASEDGE_BACKUP_BIN_PATH=${WORK_PATH}/edge_backup

LOG_PATH=""

SITE_SCRIPT_DIR="software/edge_site/edge_manager/src/script"
SCRIPT_PATH=${WORK_PATH}/${SITE_SCRIPT_DIR}

#SITE_PYTHON_PATH="${WORK_PATH}/software/edge_site/edge_manager/src/python/"

# log code independent

# get log path
configfile="${WORK_PATH}/config/config.ini"
section="SYS"
item="log_path"
ATLASEDGE_LOG_PATH=$(awk -F '=' '/\['${section}'\]/{a=1} (a==1 && "'${item}'"==$1){a=0;print $2}' ${configfile})
LMS_LOG_PATH=$(dirname ${ATLASEDGE_LOG_PATH})/lms/
ATLASEDGE_LOG_FILE=atlasedge_script.log
A500_EFFECT_FLAG="${WORK_PATH}/effect_flag"

# MODE_NAME="atlasedge"
date_format="+%Y-%m-%dT%T"

# import log and common functions
. ${SCRIPT_PATH}/log_util.sh
. ${SCRIPT_PATH}/common.sh


if [ ! -d ${ATLASEDGE_LOG_PATH} ]; then
  mkdir -p ${ATLASEDGE_LOG_PATH} && chmod -R 700 ${ATLASEDGE_LOG_PATH}
fi
if [ ! -f ${ATLASEDGE_LOG_PATH}/${ATLASEDGE_LOG_FILE} ]; then
  touch ${ATLASEDGE_LOG_PATH}/${ATLASEDGE_LOG_FILE} && chmod 600 ${ATLASEDGE_LOG_PATH}/${ATLASEDGE_LOG_FILE}
fi
if [ ! -d ${LMS_LOG_PATH} ]; then
  mkdir -p ${LMS_LOG_PATH} && chown HwHiAiUser:HwHiAiUser ${LMS_LOG_PATH} && chmod -R 700 ${LMS_LOG_PATH}
fi

function exit_trap()
{
    trap - INT TERM EXIT QUIT ABRT
    logger_Info "edge upgrade effect exit pid: $$"
}

function copy_enc_for_ha(){
    mkdir -p /home/data/ha/module/hacom/conf/config/main/config/work
    mkdir -p /home/data/ha/module/hacom/conf/config/bak/config/work
    cp -f /home/data/config/main/config/work/.baseMcsCert.enc /home/data/ha/module/hacom/conf/config/main/config/work/.default1.enc
    cp -f /home/data/config/main/config/work/.baseMcsCert.enc /home/data/ha/module/hacom/conf/config/bak/config/work/.default1.enc
    cp -f /home/data/config/main/config/work/.userMcsCert.enc /home/data/ha/module/hacom/conf/config/main/config/work/.default2.enc
    cp -f /home/data/config/main/config/work/.userMcsCert.enc /home/data/ha/module/hacom/conf/config/bak/config/work/.default2.enc
    cp -f /home/data/config/main/config/work/.ipc.enc /home/data/ha/module/hacom/conf/config/main/config/work/.default3.enc
    cp -f /home/data/config/main/config/work/.ipc.enc /home/data/ha/module/hacom/conf/config/bak/config/work/.default3.enc
}

# check Atlas 500 effect flag after reboot and process effect
function check_and_effect_A500_packets() {
    if [ ! -f "${A500_EFFECT_FLAG}" ]; then
        logger_Debug "A500 effect flag:${A500_EFFECT_FLAG} not exists"
        return ${ret_ok}
    fi

    if [ -f $WORK_PATH/import_esp_config.flag ]; then
        logger_Info "start process 500 effect"
        check_and_import_old_espm_config
        ret=$?
        if [ $ret -ne 0 ]; then
            logger_Warn "import old espm config failed"
        fi
        copy_enc_for_ha
        remove_A500_effect_flag
        exec_mod_backup_process stop
        return $ret
    fi

    effect_A500_packets
    ret=$?
    if [ $ret -ne 0 ]; then
        logger_Warn "effect Atlas 500 packets failed"
    fi
    remove_A500_effect_flag
    return ${ret_effect_restart}
}

# exec the backup operation in case power down or process down
check_if_exec_backup(){
    # check task file exist
    if [ ! -f ${WORK_PATH}/run_task ]; then
        return 0
    fi

    # check file task is upgrade
    task=`cat ${WORK_PATH}/run_task |grep "task" | cut -d":" -f2`
    if [ "$task" != "upgrade" ]; then
        return 0
    fi

    logger_Info "edge main backup check task:$task step:$step begin"

    step=`cat ${WORK_PATH}/run_task |grep "step" | cut -d":" -f2`
    if [ "$step" != "upgrade_backuped" ]; then
        logger_Info "edge main backup check task:$task step:$step no backup ret"
        return 0
    fi

    if [ -d ${ATLASEDGE_BACKUP_BIN_PATH} ]; then
        logger_Info "edge main backup recovery backup exec"
        cp -rf ${ATLASEDGE_BACKUP_BIN_PATH}/software ${WORK_PATH}/
        cp -f ${ATLASEDGE_BACKUP_BIN_PATH}/edge_main.sh ${WORK_PATH}/
        cp -rf ${ATLASEDGE_BACKUP_BIN_PATH}/version.xml ${WORK_PATH}/
        cp -rf ${ATLASEDGE_BACKUP_BIN_PATH}/run.sh ${WORK_PATH}/
    else
        logger_Info "edge main backup no back exec"
    fi

    logger_Info "edge main backup check task:$task step:$step rm task file"
    rm ${WORK_PATH}/run_task
    return 1
}

# 检测是否需要执行升级动作，如果需要执行升级替换操作
function check_and_exec_upgrade() {
    # 检测是否存在升级包 是否执行升级
    checkIsHasPreUpgradePacket
    if [ $? -eq 0 ]; then
        logger_Info "no need upgrade"
        return $ret_no_need_upgrade
    fi
    logger_Info "start to upgrade effect atlasedge"

    # 检测是否满足升级条件
    precheckEnv
    if [ $? -ne 0 ]; then
        logger_Warn "check space fail"
        return ${ret_no_satisfy_upgrade_condition}
    fi

    if [ ! -d ${ATLASEDGE_BACKUP_BIN_PATH} ]; then
        mkdir -p ${ATLASEDGE_BACKUP_BIN_PATH}
    fi

    # set upgrade flag
    set_upgrade_progress ${WORK_PATH} $UPGRADE_BACKUP_FINISH
    ret=$?
    if [ ${ret} != 0 ];then
        logger_Warn "set upgrade process failed"  ${ret}
        return ${ret_failed_set_upgrade_process_failed}
    fi

    # del work path file and copy upgrading file
    rm -rf ${WORK_PATH}/software ${WORK_PATH}/run.sh ${WORK_PATH}/version.xml

    # 拷贝文件到工作目录
    copy_file_to_work_dir
    ret=$?
    if [ $ret != 0 ];then
        logger_Warn "upgrade copyFile failed"
        return $ret
    fi

    # 升级后先调入新common
    . ${SCRIPT_PATH}/common.sh

    set_file_link $WORK_PATH
    ret=$?
    if [ $ret != 0 ];then
        logger_Warn "upgrade set file link failed"
        return $ret
    fi

    # 升级替换成功 返回重启标志 执行重启命令
    return ${ret_upgrade_ok_need_restart}
}

# config file resume
exec_configfile_resume()
{
    ${SCRIPT_PATH}/config_resume.sh
}

# clear ESPM config import flag
function clear_import_espm_config_flag()
{
    rm -f $WORK_PATH/import_esp_config.flag
}

function transferHACfg()
{
    EdgeHaHandleCfgPath="config/ha_handler/"
    HAConfigPath="/home/data/ies/"
    RedunCert="redun_import_cert.ini"
    RedunConfig="redun_base_config.ini"
    Tag="tag.ini"
    HaarbCfgSyncPy="software/edge_site/edge_manager/src/python/haarb_sync.py"

    if [ ! -d "${WORK_PATH}/$EdgeHaHandleCfgPath" ];then
        mkdir -p ${WORK_PATH}/$EdgeHaHandleCfgPath
        if [ $? -ne 0 ];then
            return $Err_MkHaHandlerFailed
        fi
    fi

    if [ -f ${HAConfigPath}/${RedunCert} ];then
        cp ${HAConfigPath}/${RedunCert} ${WORK_PATH}/${EdgeHaHandleCfgPath}
        if [ $? -ne 0 ];then
            return $Err_CpHAConfigFailed
        fi
    fi

    if [ -f ${HAConfigPath}/${RedunConfig} ];then
        cp ${HAConfigPath}/${RedunConfig} ${WORK_PATH}/${EdgeHaHandleCfgPath}
        if [ $? -ne 0 ];then
            return $Err_CpHAConfigFailed
        fi
        ${PYTHON3} ${WORK_PATH}/${HaarbCfgSyncPy}
    fi

    if [ -f ${HAConfigPath}/NODE_ID ];then
        cp ${HAConfigPath}/NODE_ID ${WORK_PATH}/${EdgeHaHandleCfgPath}
        if [ $? -ne 0 ];then
            return $Err_CpHAConfigFailed
        fi
    fi

    if [ -f ${HAConfigPath}/${Tag} ];then
        cp ${HAConfigPath}/${Tag} ${WORK_PATH}/${EdgeHaHandleCfgPath}
        if [ $? -ne 0 ];then
            return $Err_CpHAConfigFailed
        fi
    fi

    # 修改ha_handle配置目录属主
    chown -R HwHiAiUser:HwHiAiUser ${WORK_PATH}/${EdgeHaHandleCfgPath}

    return 0
}

function transferEdgeCoreCfg()
{
    export PYTHONPATH="${WORK_PATH}/software/edge_site/opensource"
    EdgeCoreDB="/opt/FD/Edge-core/bin/edge.db"
    ConfigExportPy="software/edge_site/edge_manager/src/python/trans_config.py"

    cp ${EdgeCoreDB} ${WORK_PATH}/config
    if [ $? -ne 0 ];then
        return $Err_CpEdgeDBFailed
    fi

    ${PYTHON3} ${WORK_PATH}/${ConfigExportPy} ${WORK_PATH}/../ "FD"
    if [ $? -ne 0 ];then
        return $Err_TransEdgeCfgFailed
    fi

    return 0
}

# export pod information
function exportPodInfo()
{
    export PYTHONPATH="${WORK_PATH}/software/edge_site/opensource"
    ContainerExportPy="software/edge_site/edge_manager/src/python/saveContainnerInfo.py"
    ConfigExportPy="software/edge_site/edge_manager/src/python/trans_config.py"

    ${PYTHON3} ${WORK_PATH}/${ContainerExportPy} ${WORK_PATH}/../
    if [ $? -ne 0 ];then
        return $Err_ContainerExportPyFailed
    fi
    ${PYTHON3} ${WORK_PATH}/${ConfigExportPy} ${WORK_PATH}/../ "Web"
    if [ $? -ne 0 ];then
        return $Err_ConfigExportPyFailed
    fi

    return 0
}

# clean local container
function deleteLocalContainer()
{
    docker stop $(docker ps -a -q)
    docker  rm $(docker ps -a -q)
}

function trans_sys_info()
{
    NODE_ID_PATH="/home/data/ies/NODE_ID"

    if [ -f $NODE_ID_PATH ]; then
        node_id=`cat $NODE_ID_PATH`
        if [ "${node_id}" !=  "" ]; then
            sed -i "s|nodeId:.*|nodeId: ${node_id}|g" ${WORK_PATH}/${CORE_CONFIG_FILE}
        else
            logger_Info "node-id get null"
        fi
    fi
}

# import previous old configuration for Atlas 500
function check_and_import_old_espm_config()
{
    exec_configfile_resume

    exec_mod_backup_process start
    sleep 1

    NODEINFO="/opt/IEF/NODE_INFO"

    if [ -f /home/data/ies/DoubleManagerMode ];then
        espm_net_manager_mode="DualManager"
    elif [ -f /opt/IEF/NODE_INFO ];then
        espm_net_manager_mode=`grep "net_manager" /opt/IEF/NODE_INFO | awk -F ":" '{ print $2 }' | sed 's/\r$//g' | tr -d " "`
    else
        espm_net_manager_mode="Web"
    fi

    transferHACfg
    ret=$?
    if [ $ret -ne 0 ];then
        logger_Warn "transfer ha config failed:$ret"
        clear_import_espm_config_flag
        return $ret
    fi

    if [ $espm_net_manager_mode == "FD" ];then
        transferEdgeCoreCfg
        ret=$?
        if [ $ret -ne 0 ];then
            logger_Warn "transfer edge config failed:$ret"
            clear_import_espm_config_flag
            return $ret
        fi
        logger_Info "transfer edge config success:$ret"

        deleteLocalContainer
        cp $NODEINFO $WORK_PATH/config/NODE_INFO
        ret=$?
        if [ $ret -ne 0 ];then
            logger_Warn "copy NODE_INFO failed:$ret"
            clear_import_espm_config_flag
            return $ret
        fi
        echo "manufacturer: huawei" >> $WORK_PATH/config/NODE_INFO

        logger_Info "copy NODE_INFO success:$ret"
    elif [ $espm_net_manager_mode == "Web" ];then
        exportPodInfo
        ret=$?
        if [ $ret -ne 0 ];then
            logger_Warn "export pod info failed:$ret"
            clear_import_espm_config_flag
            return $ret
        fi
        logger_Info "export pod info success:$ret"

        deleteLocalContainer
        logger_Info "delete Local Container:$?"

        trans_sys_info

    elif [ $espm_net_manager_mode == "IEF" ];then
        cp $NODEINFO $WORK_PATH/config/NODE_INFO
        ret=$?
        if [ $ret -ne 0 ];then
            logger_Warn "copy NODE_INFO failed:$ret"
            clear_import_espm_config_flag
            return $ret
        fi
        echo "manufacturer: huawei" >> $WORK_PATH/config/NODE_INFO
    elif [ $espm_net_manager_mode == "DualManager" ];then
        transferEdgeCoreCfg
        ret=$?
        if [ $ret -ne 0 ];then
            logger_Warn "transfer edge config failed:$ret"
            clear_import_espm_config_flag
            return $ret
        fi
        logger_Info "transfer edge config success:$ret"

        cp $NODEINFO $WORK_PATH/config/NODE_INFO
        ret=$?
        if [ $ret -ne 0 ];then
            logger_Warn "copy NODE_INFO failed:$ret"
            clear_import_espm_config_flag
            return $ret
        fi
        cp /home/data/ies/DoubleManagerMode ${WORK_PATH}/config/
        ret=$?
        if [ $ret -ne 0 ];then
            echo "$(date ${date_format}) copy DoubleManagerMode failed:$ret" >> ${UpgradgeLog}
            return $ret
        fi
        echo "manufacturer: huawei" >> $WORK_PATH/config/NODE_INFO
    else
        trans_sys_info
    fi

    clear_import_espm_config_flag
}

function remove_A500_effect_flag() {
    rm -f "${A500_EFFECT_FLAG}"
    logger_Info "clean A500 effect flag:${A500_EFFECT_FLAG}"
}

function exec_mod_backup_process(){
    if [ $1 == "stop" ]; then
        for ps in `ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/mod_backup.sh | awk '{print $1}'`
        do
            kill $ps
        done
    elif [ $1 == "start" ]; then
        ${SCRIPT_PATH}/mod_backup.sh &
        mod_backup_pid=`ps -ww -eo pid,cmd | grep -v grep | grep -w ${SCRIPT_PATH}/mod_backup.sh | awk '{print $1}' | tail -n1`
        logger_Info "start mod process pid:$mod_backup_pid"
    fi
}

function effect_A500_packets() {
    effect_ha_packet
    ret=$?
    if [ $ret -ne 0 ];then
        logger_Warn "ha effect fail after reboot for atlas 500"
        return ${ret}
    fi

    effect_atlasedge_packet
    ret=$?
    if [ $ret -ne 0 ];then
        logger_Warn "edge prepare effect fail after reboot for atlas 500"
        return ${ret}
    fi
    return ${ret_ok}
}

function effect_ha_packet() {
    HA_WORK_PATH=$(ReadINIfile "${ATLASEDGE_CONFIG_FILE}" SYS ha_work_path)
    if [ ! -d "${HA_WORK_PATH}" -o -z "${HA_WORK_PATH}" ]; then
        logger_Info "find no ha work dir:$(basename ${HA_WORK_PATH}) continue"
        return ${ret_ok}
    fi

    cp -f ${HA_WORK_PATH}/ha_upgrade/software/module/hacom/script/upgrade.sh  ${HA_WORK_PATH}/module/hacom/script/upgrade.sh

    bash "${HA_WORK_PATH}/module/hacom/script/upgrade.sh" -i force -e now -w $HA_WORK_PATH -o effect
    ret=$?
    if [ $ret -ne 0 ];then
        logger_Warn "effect ha shell exec fail， ret:${ret}"
        return ${ret_effect_ha_failed}
    fi
    logger_Info "effect ha finish ,ret:${ret}"
    return ${ret_ok}
}

function effect_atlasedge_packet() {
    if [ -d $ATLASEDGE_PRE_UPGRADE_PATH/ -a -f $ATLASEDGE_PRE_UPGRADE_PATH/version.xml -a -d $ATLASEDGE_PRE_UPGRADE_PATH/software ];then
        touch $ATLASEDGE_PRE_UPGRADE_PATH/effect_flag
        backup_and_copy_upgrade_file
    else
        logger_Info "find no upgrade dir $(basename ${ATLASEDGE_PRE_UPGRADE_PATH}) continue"
   fi
   return $ret_ok
}

function backup_and_copy_upgrade_file()
{
    # backup file
    if [ -d ${ATLASEDGE_BACKUP_BIN_PATH} ]; then
        rm -rf ${ATLASEDGE_BACKUP_BIN_PATH}/software
    else
        mkdir -p $ATLASEDGE_BACKUP_BIN_PATH
    fi
    chown -R HwHiAiUser:HwHiAiUser /opt/middleware/edge_portal >/dev/null 2>&1
    cp -f ${WORK_PATH}/edge_upd_effect.sh  ${ATLASEDGE_BACKUP_BIN_PATH}/
    cp -arf ${WORK_PATH}/software ${WORK_PATH}/edge_main.sh ${WORK_PATH}/run.sh ${WORK_PATH}/version.xml ${ATLASEDGE_BACKUP_BIN_PATH}/
    if [ $? -ne 0 ]; then
        logger_Warn "move file failed"
        # rm -rf ${ATLASEDGE_BACKUP_BIN_PATH}
        return ${ret_failed_copy_file_failed}
    fi
    mv -f ${WORK_PATH}/edge_main.sh ${WORK_PATH}/edge_main.sh.back
    mv -f ${WORK_PATH}/edge_upd_effect.sh ${WORK_PATH}/edge_upd_effect.sh.back
    cp -af $ATLASEDGE_PRE_UPGRADE_PATH/software/edge_site/edge_manager/src/script/edge_main.sh ${WORK_PATH}/edge_main.sh
    cp -af $ATLASEDGE_PRE_UPGRADE_PATH/software/edge_site/edge_manager/src/script/edge_upd_effect.sh ${WORK_PATH}/edge_upd_effect.sh
    cp -af $ATLASEDGE_PRE_UPGRADE_PATH/software/edge_site/edge_manager/src/script/upgrade.sh ${WORK_PATH}/software/edge_site/edge_manager/src/script/upgrade.sh
    cp -f ${ATLASEDGE_PRE_UPGRADE_PATH}/software/edge_site/edge_manager/config/A500_capability.json ${ATLASEDGE_PRE_UPGRADE_PATH}/software/edge_site/edge_manager/config/default_capability.json
}

function checkIsHasPreUpgradePacket(){
    # 预升级路径是否存在 不存在不需要升级
    if [ ! -d ${ATLASEDGE_PRE_UPGRADE_PATH} ]; then
        logger_Info "edge pre upgrade dir not exists"
        return 0
    fi

    if [ -z ${ATLASEDGE_PRE_UPGRADE_PATH} ]; then
        logger_Info "edge pre upgrade env not defined"
        return 0
    fi

    if [ -f $ATLASEDGE_PRE_UPGRADE_PATH/effect_flag -a -f $ATLASEDGE_PRE_UPGRADE_PATH/version.xml -a -d $ATLASEDGE_PRE_UPGRADE_PATH/software ];then
        return 1
    fi

    return 0
}

# check environment for upgrading
function precheckEnv() {

    # 获取日志目录
    LOG_PATH=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS log_path`

    logger_Debug "install preCheck OK LOG_PATH:" $(basename ${LOG_PATH})
    return 0
}

function copy_prev_crl_files()
{
    crl_file="FDCrl.crl"
    crl_bak_file="FDCrl.crl.bak"

    prev_crl_file="${ATLASEDGE_PRE_UPGRADE_PATH}/software/edge_core/certFD/$crl_file"
    prev_crl_bak_file="${ATLASEDGE_PRE_UPGRADE_PATH}/software/edge_core/certFD/$crl_bak_file"

    if [[ -e /etc/redhat-release ]] && [[ ! -e /etc/lsb-release ]]; then
        crl_dir="/etc/pki/ca-trust/source/anchors"
    else
        crl_dir="/usr/local/share/ca-certificates"
    fi

    curr_crl_file="$crl_dir/$crl_file"
    curr_crl_bak_file="$crl_dir/$crl_bak_file"

    if [[ ! -e ${curr_crl_file} && -e ${prev_crl_file} ]]; then
        cp -f ${prev_crl_file} ${curr_crl_file}
        rm -f ${prev_crl_file}
        logger_Info "copy crl file"
    fi

    if [[ ! -e ${curr_crl_bak_file} && -e ${prev_crl_bak_file} ]]; then
        cp -f ${prev_crl_bak_file} ${curr_crl_bak_file}
        rm -f ${prev_crl_bak_file}
        logger_Info "copy crl backup file"
    fi
}

# copy software file to work directory
function copy_file_to_work_dir() {
    copy_prev_crl_files

    # 出错信息是否到 配置文件中 如果拷贝出错 待完善 ！！
    cp -rf ${ATLASEDGE_PRE_UPGRADE_PATH}/software  ${WORK_PATH}/
    ret=$?
    if [ "$ret" != "0" ]; then
        logger_Warn "copy software file  failed ret=$ret"
        return ${ret_failed_copy_file_failed};
    fi

    # 拷贝版本信息文件
    cp -rf ${ATLASEDGE_PRE_UPGRADE_PATH}/version.xml  ${WORK_PATH}/
    if [ "$?" != "0" ]; then
        logger_Warn "copy version file failed"
        return ${ret_failed_copy_file_failed};
    fi

    # 移动
    mv -f ${WORK_PATH}/${SITE_SCRIPT_DIR}/edge_main.sh  ${WORK_PATH}/
    if [ "$?" != "0" ]; then
        logger_Warn "mv edge_main failed"
        return ${ret_failed_copy_file_failed};
    fi
    mv -f ${WORK_PATH}/${SITE_SCRIPT_DIR}/run.sh  ${WORK_PATH}/
    if [ "$?" != "0" ]; then
        logger_Warn "cp run.sh file failed"
        return ${ret_failed_copy_file_failed};
    fi
    chmod -R 700 ${WORK_PATH}/edge_main.sh
    chmod -R 700 ${WORK_PATH}/run.sh
    chmod -R 700 ${WORK_PATH}/software/IEF/edge-installer/conf/script/*

    # 刷新路径信息
    flush_path_info
    if [ "$?" != "0" ]; then
        logger_Warn "copy flush path info failed"
        return ${ret_failed_copy_file_failed};
    fi

    # get install type config
    file="${WORK_PATH}/config/config.ini"
    section="SYS"
    item="install_type"
    INSTALL_TYPE=$(awk -F '=' '/\['${section}'\]/{a=1} (a==1 && "'${item}'"==$1){a=0;print $2}' ${file})

    # set install plugin info
    set_install_type ${INSTALL_TYPE} ${WORK_PATH}

    cat ${WORK_PATH}/config/user_set_capablity.json 2>>/dev/null | grep 'ha_config'
    if [ $? -eq 0 ];then
        sed -i "s|is_enabled=.*|is_enabled=True|g" ${WORK_PATH}/software/edge_site/ha_handler/config/config.ini
    else
        sed -i "s|is_enabled=.*|is_enabled=False|g" ${WORK_PATH}/software/edge_site/ha_handler/config/config.ini
    fi

    copy_webfile_to_webworkdir /opt/middleware
    ret=$?
    if [ $ret -ne 0 ];then
        logger_Warn "webfile copy failed:$ret"
        return $ret
    fi
    chown -R HwHiAiUser:HwHiAiUser "${WORK_PATH}"
    return ${ret_ok}
}

# refresh environment parameter and paths in script and config file
flush_path_info(){
    # 更新配置
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/software/edge_site/edge_manager/config/atlasedge.service

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/run.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/run.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/uninstall.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/uninstall.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config.sh

    sed -i "s|{service_path}|${WORK_PATH}/software/edge_site/edge_manager/config|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/start.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/start.sh
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/start.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/stop.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/stop.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/upgrade.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/upgrade.sh

    sed -i "s|{log_path}|${LOG_PATH}|g" ${WORK_PATH}/software/edge_site/common/log/logging.cfg

    sed -i "s|{log_path}|${LOG_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/log_util.sh

    sed -i "s|{log_path}|${LOG_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mdw_log_retate_by_size.sh
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_workkey.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_workkey.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/software/edge_site/ha_handler/scripts/config_hahandler.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config_resume.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config_resume.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_backup.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_backup.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/ha_status_monitor.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_file_list.txt
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_file_list.txt

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/updateCRL.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/updateCRL.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_software_CRL.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_software_CRL.sh
}

function is_a500_device() {
    cat ${WORK_PATH}/config/default_capability.json  | grep esp_enable | grep true > /dev/null 2>&1
}

function copy_webfile_to_webworkdir(){
    # if not Atlas 500 device, skip copy web file
    is_a500_device
    if [ $? -ne 0 ]; then
        return 0
    fi

    EDGE_WORK_DIR=$1
    logger_Info "start copy webfile copy"
    if [ ! -d ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal ];then
        logger_Warn "web file not find exit"
        return $Err_WebFileNotExist
    fi

    mkdir -p ${EDGE_WORK_DIR}/edge_portal
    cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/src ${EDGE_WORK_DIR}/edge_portal
    chown -R nobody:nobody ${EDGE_WORK_DIR}/edge_portal

    if [ -d  /usr/local/nginx/html/manager/i18n/ ]; then
        cp -f ${WORK_PATH}/software/edge_portal/alarm.xml/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/en-US/
        cp -f ${WORK_PATH}/software/edge_portal/alarm.xml/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/zh-CN/
    chown nobody:nobody /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml
    chmod 400 /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml
    fi

    if [ -d  /usr/local/nginx/html/manager/src/onlinehelp ]; then
        cp -rf ${WORK_PATH}/software/edge_portal/help/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/en/
        cp -rf ${WORK_PATH}/software/edge_portal/help/zh/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/
        chown -R nobody:nobody /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
        chmod 400 /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
    fi

    logger_Info "webfile copy success:$ret"
    return 0
}

# clear upgrade file, call after upgrade proc
clear_upgrade_file(){
    logger_Info "clear upgrade file upgradePath:${ATLASEDGE_PRE_UPGRADE_PATH}"

    if [ "${ATLASEDGE_PRE_UPGRADE_PATH}" != "" -a -d "${ATLASEDGE_PRE_UPGRADE_PATH}" ];then
        rm -rf ${ATLASEDGE_PRE_UPGRADE_PATH}
    fi
    [ -f ${WORK_PATH}/edge_main.sh.back ] && rm -f  ${WORK_PATH}/edge_main.sh.back
    [ -f ${WORK_PATH}/edge_upd_effect.sh.back ] && rm -f ${WORK_PATH}/edge_upd_effect.sh.back
    set_upgrade_progress $WORK_PATH $UPGRADE_DONE
}

set_upgrade_result()
{
    result=$1
    errcode=$2
    reason=$3

    if [ -f ${WORK_PATH}/upgrade.result ];then
        rm -f ${WORK_PATH}/upgrade.result
    fi

    echo "[SYS]" >> ${WORK_PATH}/upgrade.result
    echo "result=$result" >> ${WORK_PATH}/upgrade.result
    echo "errcode=$errcode" >> ${WORK_PATH}/upgrade.result
    echo "reason=$reason" >> ${WORK_PATH}/upgrade.result
    chown HwHiAiUser:HwHiAiUser ${WORK_PATH}/upgrade.result
}

function RecoveryBackup() {
    if [ -d ${ATLASEDGE_BACKUP_BIN_PATH} ]; then
        logger_Info "recovery backup exec"
        cp -arf ${ATLASEDGE_BACKUP_BIN_PATH}/software ${WORK_PATH}/
        cp -af ${ATLASEDGE_BACKUP_BIN_PATH}/edge_main.sh ${WORK_PATH}/
        cp -af ${ATLASEDGE_BACKUP_BIN_PATH}/version.xml ${WORK_PATH}/
        cp -af ${ATLASEDGE_BACKUP_BIN_PATH}/run.sh ${WORK_PATH}/
    fi

    return 0
}

function edge_ensure_privilege() {
    copy_webfile_to_webworkdir /opt/middleware

    chmod +x ${SCRIPT_PATH}/privilege_config.sh
    LOG_PATH=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS log_path`
    ${SCRIPT_PATH}/privilege_config.sh ${WORK_PATH} ${LOG_PATH} /home/data/config > /dev/null 2>&1

    local ha_work_path="$(ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS ha_work_path)"
    local ha_privilege_config="${ha_work_path}/module/hacom/script/privilege_config.sh"
    if [ -f "$ha_privilege_config" ]; then
        bash ${ha_work_path}/module/hacom/script/privilege_config.sh ${ha_work_path} /var/alog/ha /home/data/ha
        ret=$?
        logger_Info "config ha privilege return $ret"
    else
        logger_Warn "ha privilege config file not found"
    fi

    logger_Info "check and ensure software privilege ret:$?"
}

main() {
    trap exit_trap INT TERM EXIT QUIT ABRT
    logger_Info "edge upd effect begin pid: $$ ars:$# arg1:$1"

    # check if Atlas 500 upgrade reboot, need to effect
    check_and_effect_A500_packets
    ret=$?
    if [ $ret -eq $ret_effect_restart ]; then
        logger_Info "A500 effect flag set restart"
        return $ret
    elif [ $ret -ne 0 ]; then
        logger_Warn "check effect A500 packets failed, ret:${ret} contine"
        return $ret
    fi

    # check if power down of system terminate, execute backup resume
    check_if_exec_backup
    ret=$?
    if [ $ret == 1 ]; then
        logger_Warn "exec backup restart"
        return $ret_backup_finish_restart
    fi

    # check if need replace file for upgrade
    check_and_exec_upgrade
    ret=$?
    if [ $ret -eq ${ret_upgrade_ok_need_restart} ]; then
        logger_Info "edge main exec upgrade replace OK so restart"
        clear_upgrade_file
        set_upgrade_result "success" 0 "success"
        # 退出重启启动
        return ${ret_ok}
    elif [ $ret -eq $ret_no_need_upgrade ]; then
        # 增加第一个参数upgrade  表示为单纯升级操作 退出 待完善 返回升级结果 如果安装过程没有执行也是个问题，要增加返回判断
        if  [ $# == 1 -a "$1" == "upgrade" ]; then
            set_upgrade_result "failed" $ret "no need upgrade"
            return $ret
        fi
    # ret_ok为升级成功场景 其他场景为失败场景，执行回退操作
    elif [ $ret -ne ${ret_ok} ]; then
        logger_Warn "upgrade failed ret:$ret"
        RecoveryBackup
        clear_upgrade_file
        set_upgrade_result "failed" $ret "upgrade failed"
        # 是否增加重启
        return $ret
    fi

    return ${ret_ok}
}

logger_Info "start to check if need upgrade or effect"
main "$@"
RESULT=$?
edge_ensure_privilege
logger_Info "edge upd effect exit ret:$RESULT"
exit $RESULT